package be.kuleuven.cs.mop.gui.dialogs;


import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.util.List;

import be.kuleuven.cs.mop.app.controllers.Controllers;
import be.kuleuven.cs.mop.domain.exceptions.InvalidCurrentUserException;
import be.kuleuven.cs.mop.domain.model.Resource;
import be.kuleuven.cs.mop.domain.model.ResourceType;
import be.kuleuven.cs.mop.gui.components.ActionButton;
import be.kuleuven.cs.mop.gui.components.ComboSelector;
import be.kuleuven.cs.mop.gui.components.TextInput;
import be.kuleuven.cs.mop.gui.util.SwingUtils;



/**
 * {@link ActionDialog} for the "Create Resource" use case
 */
public class CreateResourceDialog extends ActionDialog {
	private static final long serialVersionUID = 1L;
	
	private TextInput					input	= new TextInput();
	private ComboSelector<ResourceType>	list;
	
	
	public CreateResourceDialog(final Frame parent, final Controllers controllers) {
		super(parent, "Create Resource", controllers);
		final GridBagConstraints gbc = SwingUtils.getGBC();
		
		final List<ResourceType> types;
		try {
			types = getControllers().getControllerResources().getResourceTypes();
		} catch (final InvalidCurrentUserException e) {
			log(e);
			dispose();
			return;
		}
		
		list = new ComboSelector<ResourceType>(
				types.toArray(new ResourceType[types.size()]));
		gbc.gridx	= 0;
		gbc.gridy	= 0;
		add(list, gbc);
		
		input.setToolTipText("Enter the description for the resource");
		gbc.gridy	= 1;
		add(input, gbc);
		
		gbc.gridy	= 2;
		add(new ActionButton("Create", new Dimension(150, 32), this), gbc);
		
		display();
	}
	
	
	
	@Override
	protected void handle(final ActionEvent event) {
		try {
			final Resource resource =
				getControllers().getControllerResources().createResource(
						list.getSelection(), input.read());
			log("Created resource '%s'", resource.getDescription());
			dispose();
		} catch (final Exception e) {
			log(e);
		}
	}
	
}